package com.after.saas.oauth.service.impl;


import com.after.saas.oauth.domain.MessageConstant;
import com.after.saas.oauth.domain.SecurityUser;
import com.after.saas.oauth.domain.UserDTO;
import com.after.saas.oauth.service.UmsAdminService;
import com.after.saas.oauth.service.UmsMemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * UserDetailsServiceImpl
 *
 * @author hjchen
 * @date 2019/3/30
 */
@Slf4j
@Service
public class UserServiceImpl implements UserDetailsService {
    /**
     * 后台管理client_id
     */
    String ADMIN_CLIENT_ID = "admin-app";

    private final UmsAdminService adminService;
    private final UmsMemberService memberService;
    private final HttpServletRequest httpServletRequest;


    public UserServiceImpl(HttpServletRequest httpServletRequest, UmsAdminService adminService, UmsMemberService memberService) {
        this.httpServletRequest = httpServletRequest;
        this.adminService = adminService;
        this.memberService = memberService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String clientId = httpServletRequest.getParameter("client_id");
        log.info("username is {} clientId {}", username, clientId);
        UserDTO userDto;
        if (ADMIN_CLIENT_ID.equals(clientId)) {
            userDto = adminService.loadUserByUsername(username);
            log.info("userDto \n{}", userDto);
        } else {
            userDto = memberService.loadUserByUsername(username);
        }
        if (userDto == null) {
            throw new UsernameNotFoundException(MessageConstant.USERNAME_PASSWORD_ERROR);
        }
        userDto.setClientId(clientId);
        SecurityUser securityUser = new SecurityUser(userDto);
        if (!securityUser.isEnabled()) {
            throw new DisabledException(MessageConstant.ACCOUNT_DISABLED);
        } else if (!securityUser.isAccountNonLocked()) {
            throw new LockedException(MessageConstant.ACCOUNT_LOCKED);
        } else if (!securityUser.isAccountNonExpired()) {
            throw new AccountExpiredException(MessageConstant.ACCOUNT_EXPIRED);
        } else if (!securityUser.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException(MessageConstant.CREDENTIALS_EXPIRED);
        }
        return securityUser;
    }
}
